// pages/my/commonSettings.js
import { ComponentWithStore } from "mobx-miniprogram-bindings";
import { userStore } from "../../store/userStore";
import { clearStorage, setStorage } from "../../utils/storage";
import { getUserInfoService, updateUserInfo } from "../../api/user";
import { getStorage } from "../../utils/storage";
import http from "../../utils/http";

ComponentWithStore({
  /**
   * 页面的初始数据
   */
  data: {
    emailChange: false,
    tempEmail: '',
    phoneNumChange: false,
    tempPhoneNum: '',
  },

  storeBindings: {
    store: userStore,
    fields: ["token", "userInfo", "isLogin"],
    actions: ["setToken", "setUserInfo", "setIsLogin"],
  },

  methods: {
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      console.log('CommonSettings page loaded');
      wx.setNavigationBarTitle({
        title: '通用设置'
      });
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      
    },

    changeEmail: async function ()
    {
      this.setData({
        emailChange: true
      });
    },

    onEmailInput(e) {
      this.setData({
        tempEmail: e.detail.value
      });
    },
  
    async onConfirmEmail() {
      const email = this.data.tempEmail.trim();
      // 校验
      if (!email.includes('@') || !email.includes('.')) {
        wx.showToast({
          title: '看起来像是一个无效邮箱',
          icon: 'none'
        });
        return;
      }

      // @ 位置不能在开头或结尾
      const atIndex = email.indexOf('@');
      if (atIndex <= 0 || atIndex === email.length - 1)
      {
        wx.showToast({
          title: '看起来像是一个无效邮箱',
          icon: 'none'
        });
        return;
      }

      // . 必须在 @ 之后
      const dotIndex = email.lastIndexOf('.');
      if (dotIndex < atIndex + 2 || dotIndex === email.length - 1) {
        wx.showToast({
          title: '看起来像是一个无效邮箱',
          icon: 'none'
        });
        return;
      }

      wx.showToast({
        title: '上传中...',
        icon: 'loading',
        duration: 800
      })
      try {
        const res = await updateUserInfo(this.data.userInfo, {email: email});
        console.log("邮件修改成功", res);

        const { data } = await getUserInfoService();
        setStorage("userInfo", data);
        this.setUserInfo(data);
        this.setData({
          "userInfo.email": email,
          tempEmail: ''
        })

        wx.showToast({
          title: '修改邮箱成功',
          icon: 'success',
          duration: 2000
        });
        this.cancelEmailChange();
      } catch (err) {
        console.error("邮件修改失败", err);
        this.setData({
          tempEmail: ''
        })
      }
    },

    cancelEmailChange()
    {
      this.setData({
        emailChange: false
      });
    },

    changePhoneNum()
    {
      this.setData({
        phoneNumChange: true
      });
    },

    onPhoneNumInput(e) {
      this.setData({
        tempPhoneNum: e.detail.value
      });
    },
  
    async onConfirmPhoneNum() {
      const phone = this.data.tempPhoneNum.trim();
      // 简单校验 必须是 11 位纯数字
      const phoneRegex = /^\d{11}$/;
      if (!phoneRegex.test(phone))
      {
        wx.showModal({
          title: '提示',
          content: '请输入正确的11位手机号码',
          showCancel: false,
        });
        return;
      }

      wx.showToast({
        title: '上传中...',
        icon: 'loading',
        duration: 800
      })
      try {
        const res = await updateUserInfo(this.data.userInfo, {phone: phone});
        console.log("电话修改成功", res);

        const { data } = await getUserInfoService();
        setStorage("userInfo", data);
        this.setUserInfo(data);
        this.setData({
          "userInfo.phone": phone,
          tempPhoneNum: ''
        })

        wx.showToast({
          title: '修改电话成功',
          icon: 'success',
          duration: 2000
        });
        this.cancelPhoneNumChange();
      } catch (err) {
        console.error("电话修改失败", err);
        this.setData({
          tempPhoneNum: ''
        })
      }
    },

    cancelPhoneNumChange()
    {
      this.setData({
        phoneNumChange: false
      });
    },

    logout() {
      clearStorage();
      this.setToken("");
      this.setUserInfo("");
      this.setIsLogin(false);
      // 跳转首页
      wx.reLaunch({
        url: "../index/index",
      });
    },

    async listfile()
    {
      console.log(getStorage('token'))
      try {
        const res = await http.post(`/fileUploadController/querImgList`)
        console.log('list succeeded', res)
      } catch (err) {
        console.log('list failed', err)
      }
    },
  },
});